<?php

namespace App\Supports\Payment\Methods\Balance;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Events\OrderPaidEvent;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;

class PayOrder extends Method implements MethodPay
{
	protected function isBalanceEnough($order)
	{
		return big_decimal($order->user->balance)
			->isGreaterThanOrEqualTo($order->total_amount);
	}
	
	public function validate($order = null)
	{

		if ($order->isPaid()) {
			fail('目标订单已支付');
		}
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($order->isCancelled()) {
			fail('目标订单已取消');
		}
		if (!$this->isBalanceEnough($order)) {
			fail('可用账户余额不足');
		}
	}
	
	public function info($order = null) {}
	
	public function pay($order = null)
	{

		$this->validate($order);
		return DB::transaction(function () use ($order) {
			$order = Order::find($order->id);
			$order->update(['paid_at' => Carbon::now(), 'paid_method' => 'balance']);
			$balances = $order->total_amount;
            $data = ['order_id' => $order->id];
            account_balances($order->user)->minusOrderPaid($balances, $data);
            if($order->user_coupon_id){
            	UserCoupon::find($order->user_coupon_id)->update(['is_used'=>1]);
            }

            if($order->user->parent_id){
                $parentUser = User::find($order->user->parent_id);
                $orderItem = OrderItem::query()->where('order_id',$order->id)->first();
                $data['product_id'] = $orderItem->product_id;
                $data['product_sku_id'] = $orderItem->product_sku_id;
                account_brokerages($parentUser)->orderPaid(10, $data);

            }
            
			event(new OrderPaidEvent($order));
			$order->unsetRelations();
			return $order;
		
		});
	}
}
